#!/usr/bin/env python3
"""
通讯录路由
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import db, Contact
from datetime import datetime
import json
import csv
import io

bp = Blueprint('contacts', __name__)


@bp.route('/', methods=['GET'])
@jwt_required()
def get_contacts():
    """获取联系人列表，支持分页/筛选/排序
    查询参数：
      - page: 页码（默认1）
      - per_page: 每页数量（默认20）
      - q: 文本搜索（模糊匹配 name, phone, email, company）
      - group: 分组筛选
      - tags: 标签筛选（逗号分隔）
      - is_favorite: 收藏状态筛选（true/false）
      - sort: 排序字段（name, created_at, -name, -created_at，默认 -created_at）
    """
    try:
        current_user_id = int(get_jwt_identity())

        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        q = request.args.get('q', type=str)
        group = request.args.get('group', type=str)
        tags = request.args.get('tags', type=str)
        is_favorite = request.args.get('is_favorite', type=str)
        sort = request.args.get('sort', '-created_at')

        query = Contact.query.filter_by(user_id=current_user_id)

        # 文本搜索
        if q:
            search_term = f"%{q}%"
            query = query.filter(
                db.or_(
                    Contact.name.like(search_term),
                    Contact.phone.like(search_term),
                    Contact.email.like(search_term),
                    Contact.company.like(search_term)
                )
            )

        # 分组筛选
        if group:
            query = query.filter(Contact.group == group)

        # 标签筛选
        if tags:
            tag_list = [tag.strip() for tag in tags.split(',')]
            for tag in tag_list:
                query = query.filter(Contact.tags.like(f"%{tag}%"))

        # 收藏状态筛选
        if is_favorite is not None:
            if is_favorite.lower() in ('true', '1', 'yes'):
                query = query.filter(Contact.is_favorite.is_(True))
            elif is_favorite.lower() in ('false', '0', 'no'):
                query = query.filter(Contact.is_favorite.is_(False))

        # 排序
        if sort == 'name':
            query = query.order_by(Contact.name.asc())
        elif sort == '-name':
            query = query.order_by(Contact.name.desc())
        elif sort == 'created_at':
            query = query.order_by(Contact.created_at.asc())
        else:  # 默认按创建时间倒序
            query = query.order_by(Contact.created_at.desc())

        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        contacts = [contact.to_dict() for contact in pagination.items]

        return jsonify({
            'success': True,
            'contacts': contacts,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages,
                'has_next': pagination.has_next,
                'has_prev': pagination.has_prev
            }
        }), 200

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/<int:contact_id>', methods=['GET'])
@jwt_required()
def get_contact(contact_id):
    """获取单个联系人详情"""
    try:
        current_user_id = int(get_jwt_identity())
        
        contact = Contact.query.filter_by(
            id=contact_id, 
            user_id=current_user_id
        ).first()
        
        if not contact:
            return jsonify({
                'success': False,
                'error': '联系人不存在'
            }), 404
        
        return jsonify({
            'success': True,
            'contact': contact.to_dict()
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/', methods=['POST'])
@jwt_required()
def create_contact():
    """创建新联系人"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        if not data or not data.get('name'):
            return jsonify({
                'success': False,
                'error': '姓名不能为空'
            }), 400
        
        # 处理标签
        tags_str = None
        if data.get('tags') and isinstance(data['tags'], list):
            tags_str = ','.join(data['tags'])
        
        # 处理社交账号
        social_accounts_str = None
        if data.get('social_accounts'):
            social_accounts_str = json.dumps(data['social_accounts'])
        
        # 处理生日
        birthday = None
        if data.get('birthday'):
            try:
                birthday = datetime.strptime(data['birthday'], '%Y-%m-%d').date()
            except ValueError:
                pass
        
        contact = Contact(
            user_id=current_user_id,
            name=data['name'],
            phone=data.get('phone'),
            email=data.get('email'),
            address=data.get('address'),
            company=data.get('company'),
            position=data.get('position'),
            notes=data.get('notes'),
            tags=tags_str,
            birthday=birthday,
            group=data.get('group', '默认'),
            is_favorite=data.get('is_favorite', False),
            avatar=data.get('avatar'),
            social_accounts=social_accounts_str
        )
        
        db.session.add(contact)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'contact': contact.to_dict(),
            'message': '创建成功'
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/<int:contact_id>', methods=['PUT'])
@jwt_required()
def update_contact(contact_id):
    """更新联系人"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        contact = Contact.query.filter_by(
            id=contact_id,
            user_id=current_user_id
        ).first()
        
        if not contact:
            return jsonify({
                'success': False,
                'error': '联系人不存在'
            }), 404
        
        # 更新字段
        if 'name' in data:
            contact.name = data['name']
        if 'phone' in data:
            contact.phone = data['phone']
        if 'email' in data:
            contact.email = data['email']
        if 'address' in data:
            contact.address = data['address']
        if 'company' in data:
            contact.company = data['company']
        if 'position' in data:
            contact.position = data['position']
        if 'notes' in data:
            contact.notes = data['notes']
        if 'tags' in data and isinstance(data['tags'], list):
            contact.tags = ','.join(data['tags'])
        if 'birthday' in data:
            if data['birthday']:
                try:
                    contact.birthday = datetime.strptime(data['birthday'], '%Y-%m-%d').date()
                except ValueError:
                    pass
            else:
                contact.birthday = None
        if 'group' in data:
            contact.group = data['group']
        if 'is_favorite' in data:
            contact.is_favorite = data['is_favorite']
        if 'avatar' in data:
            contact.avatar = data['avatar']
        if 'social_accounts' in data:
            contact.social_accounts = json.dumps(data['social_accounts']) if data['social_accounts'] else None
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'contact': contact.to_dict(),
            'message': '更新成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/<int:contact_id>', methods=['DELETE'])
@jwt_required()
def delete_contact(contact_id):
    """删除联系人"""
    try:
        current_user_id = int(get_jwt_identity())
        
        contact = Contact.query.filter_by(
            id=contact_id,
            user_id=current_user_id
        ).first()
        
        if not contact:
            return jsonify({
                'success': False,
                'error': '联系人不存在'
            }), 404
        
        db.session.delete(contact)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '删除成功'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/batch-delete', methods=['POST'])
@jwt_required()
def batch_delete_contacts():
    """批量删除联系人"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        if not data or not data.get('ids'):
            return jsonify({
                'success': False,
                'error': '请选择要删除的联系人'
            }), 400
        
        contact_ids = data['ids']
        if not isinstance(contact_ids, list):
            return jsonify({
                'success': False,
                'error': '联系人ID列表格式错误'
            }), 400
        
        # 查询并删除
        contacts = Contact.query.filter(
            Contact.id.in_(contact_ids),
            Contact.user_id == current_user_id
        ).all()
        
        if not contacts:
            return jsonify({
                'success': False,
                'error': '未找到要删除的联系人'
            }), 404
        
        for contact in contacts:
            db.session.delete(contact)
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': f'成功删除 {len(contacts)} 个联系人'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/<int:contact_id>/favorite', methods=['PUT'])
@jwt_required()
def toggle_favorite(contact_id):
    """切换收藏状态"""
    try:
        current_user_id = int(get_jwt_identity())
        
        contact = Contact.query.filter_by(
            id=contact_id,
            user_id=current_user_id
        ).first()
        
        if not contact:
            return jsonify({
                'success': False,
                'error': '联系人不存在'
            }), 404
        
        contact.is_favorite = not contact.is_favorite
        db.session.commit()
        
        return jsonify({
            'success': True,
            'contact': contact.to_dict(),
            'message': '收藏状态已更新'
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/export', methods=['POST'])
@jwt_required()
def export_contacts():
    """导出联系人"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json() or {}
        
        format_type = data.get('format', 'csv')  # csv 或 json
        contact_ids = data.get('ids')  # 如果指定，只导出选中的联系人
        
        query = Contact.query.filter_by(user_id=current_user_id)
        
        if contact_ids and isinstance(contact_ids, list):
            query = query.filter(Contact.id.in_(contact_ids))
        
        contacts = query.all()
        
        if format_type == 'json':
            contacts_data = [contact.to_dict() for contact in contacts]
            return jsonify({
                'success': True,
                'data': contacts_data,
                'format': 'json',
                'count': len(contacts_data)
            }), 200
        
        elif format_type == 'csv':
            # 创建CSV数据
            output = io.StringIO()
            writer = csv.writer(output)
            
            # 写入表头
            headers = ['姓名', '电话', '邮箱', '公司', '职位', '地址', '分组', '标签', '生日', '备注', '收藏', '创建时间']
            writer.writerow(headers)
            
            # 写入数据
            for contact in contacts:
                row = [
                    contact.name or '',
                    contact.phone or '',
                    contact.email or '',
                    contact.company or '',
                    contact.position or '',
                    contact.address or '',
                    contact.group or '',
                    contact.tags or '',
                    contact.birthday.strftime('%Y-%m-%d') if contact.birthday else '',
                    contact.notes or '',
                    '是' if contact.is_favorite else '否',
                    contact.created_at.strftime('%Y-%m-%d %H:%M:%S') if contact.created_at else ''
                ]
                writer.writerow(row)
            
            csv_data = output.getvalue()
            output.close()
            
            return jsonify({
                'success': True,
                'data': csv_data,
                'format': 'csv',
                'count': len(contacts)
            }), 200
        
        else:
            return jsonify({
                'success': False,
                'error': '不支持的导出格式'
            }), 400
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/import', methods=['POST'])
@jwt_required()
def import_contacts():
    """导入联系人"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        if not data or not data.get('contacts'):
            return jsonify({
                'success': False,
                'error': '请提供要导入的联系人数据'
            }), 400
        
        contacts_data = data['contacts']
        if not isinstance(contacts_data, list):
            return jsonify({
                'success': False,
                'error': '联系人数据格式错误'
            }), 400
        
        imported_count = 0
        errors = []
        
        for i, contact_data in enumerate(contacts_data):
            try:
                if not contact_data.get('name'):
                    errors.append(f'第{i+1}行：姓名不能为空')
                    continue
                
                # 检查是否已存在同名联系人
                existing = Contact.query.filter_by(
                    user_id=current_user_id,
                    name=contact_data['name']
                ).first()
                
                if existing:
                    errors.append(f'第{i+1}行：联系人"{contact_data["name"]}"已存在')
                    continue
                
                # 处理标签
                tags_str = None
                if contact_data.get('tags'):
                    if isinstance(contact_data['tags'], list):
                        tags_str = ','.join(contact_data['tags'])
                    else:
                        tags_str = str(contact_data['tags'])
                
                # 处理社交账号
                social_accounts_str = None
                if contact_data.get('social_accounts'):
                    social_accounts_str = json.dumps(contact_data['social_accounts'])
                
                # 处理生日
                birthday = None
                if contact_data.get('birthday'):
                    try:
                        if isinstance(contact_data['birthday'], str):
                            birthday = datetime.strptime(contact_data['birthday'], '%Y-%m-%d').date()
                    except ValueError:
                        pass
                
                contact = Contact(
                    user_id=current_user_id,
                    name=contact_data['name'],
                    phone=contact_data.get('phone'),
                    email=contact_data.get('email'),
                    address=contact_data.get('address'),
                    company=contact_data.get('company'),
                    position=contact_data.get('position'),
                    notes=contact_data.get('notes'),
                    tags=tags_str,
                    birthday=birthday,
                    group=contact_data.get('group', '默认'),
                    is_favorite=contact_data.get('is_favorite', False),
                    avatar=contact_data.get('avatar'),
                    social_accounts=social_accounts_str
                )
                
                db.session.add(contact)
                imported_count += 1
                
            except Exception as e:
                errors.append(f'第{i+1}行：{str(e)}')
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': f'成功导入 {imported_count} 个联系人',
            'imported_count': imported_count,
            'errors': errors
        }), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/groups', methods=['GET'])
@jwt_required()
def get_groups():
    """获取所有分组"""
    try:
        current_user_id = int(get_jwt_identity())
        
        # 获取所有分组
        groups = db.session.query(Contact.group).filter_by(user_id=current_user_id).distinct().all()
        group_list = [group[0] for group in groups if group[0]]
        
        # 统计每个分组的联系人数量
        group_stats = {}
        for group in group_list:
            count = Contact.query.filter_by(user_id=current_user_id, group=group).count()
            group_stats[group] = count
        
        return jsonify({
            'success': True,
            'groups': group_list,
            'stats': group_stats
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@bp.route('/tags', methods=['GET'])
@jwt_required()
def get_tags():
    """获取所有标签"""
    try:
        current_user_id = int(get_jwt_identity())
        
        # 获取所有标签
        contacts = Contact.query.filter_by(user_id=current_user_id).all()
        all_tags = set()
        
        for contact in contacts:
            if contact.tags:
                tags = [tag.strip() for tag in contact.tags.split(',') if tag.strip()]
                all_tags.update(tags)
        
        tag_list = sorted(list(all_tags))
        
        # 统计每个标签的使用次数
        tag_stats = {}
        for tag in tag_list:
            count = Contact.query.filter(
                Contact.user_id == current_user_id,
                Contact.tags.like(f'%{tag}%')
            ).count()
            tag_stats[tag] = count
        
        return jsonify({
            'success': True,
            'tags': tag_list,
            'stats': tag_stats
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
